<template>
  <div class="market_cardactivity_qrcode">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex" justify="start" class="search-item-left">
          <Col class="search-item">
            <span class="search-label">二维码生成时间：</span>
            <DatePicker type="datetimerange" placeholder="请选择" placement="bottom-end" :editable='false' format="yyyy-MM-dd HH:mm:ss" class="data-time-style" style="width:280px;" :value="dateVal" @on-change="daterangeChange"></DatePicker>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type='primary'
                  @click="search"
                  >查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                @click="reset">重置</Button>
          </Col>
        </Row>
        <Row type="flex" justify="end" class="search-item-right">
          <Col class="search-item"><Button class="search-btn" type="primary" @click="skipAdd" v-if="hasPermission('moms:market:cardqrcreate')">新增</Button></Col>
        </Row>
      </Row>
    </div>
    <Table stripe :loading="loading" class="table-list" :columns="columns" :data="data" :height="tableHeight">
      <template slot-scope="{ row }" slot="action">
        <i class="iconsys iconxiajia" title="导出二维码表格" @click="output(row, '1')" v-if="hasPermission('moms:market:cardqrexport')"></i>
        <i class="iconsys iconxiajia" title="导出二维码图片" @click="output(row, '2')" v-if="hasPermission('moms:market:cardqrexport')"></i>
      </template>
    </Table>
    <Row type='flex' justify="end" style='padding: 20px'>
      <Col>
        <Page :total="total"
              :page-size='pageSize'
              :current='pageIndex'
              show-total
              show-sizer
              @on-change='changePageIndex'
              @on-page-size-change='changePageSize' />
      </Col>
    </Row>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getQRcodeLists, getQRcodeInfo } from '@/api/market/cardactivity/qrcode.js'
import { formatDate } from '@/libs/tools.js'
export default {
  name: 'market_cardactivity_qrcode',
  data () {
    return {
      dateVal: '',
      total: 0,
      pageSize: 10,
      pageIndex: 1,
      loading: false,
      tableHeight: 0,
      data: [],
      columns: [
        {
          title: '二维码生成批次',
          key: 'batchNo'
        },
        {
          title: '二维码生成数量',
          key: 'cardQty'
        },
        {
          title: '条形码生成数量',
          key: 'barcodeQty'
        },
        {
          title: '卡号段',
          key: 'cardNoSegment'
        },
        {
          title: '操作人',
          key: 'creatorName'
        },
        {
          title: '操作时间',
          key: 'createAt'
        }
      ]
    }
  },
  computed: {
    ...mapState({
      merchantId: state => state.user.merchantId
    })
  },
  watch: {
    '$route' (newRoute) {
      if (newRoute.name === 'market_cardactivity_qrcode') {
        this.getData()
      }
    }
  },
  mounted () {
    this.reset()
    if (this.hasPermission(['moms:market:cardqrexport'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        width: 150
      })
    }
  },
  methods: {
    getData () {
      this.loading = true
      this.tableHeight = 0
      getQRcodeLists({
        merchantId: this.merchantId,
        startTime: this.dateVal ? this.dateVal[0] : this.dateVal,
        endTime: this.dateVal ? this.dateVal[1] : this.dateVal,
        offset: (this.pageIndex - 1) * this.pageSize,
        limit: this.pageSize
      }).then(res => {
        this.loading = false
        const result = res.data || {}
        if (result.status === 200) {
          this.data = result.data || []
          this.total = result.totalCount || 0
          if (this.data.length > 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${result.error}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
        this.loading = false
      })
    },
    search () {
      this.pageIndex = 1
      this.getData()
    },
    reset () {
      const now = new Date()
      this.dateVal = [formatDate(new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000), 'yyyy-MM-dd hh:mm:ss'), formatDate(now, 'yyyy-MM-dd hh:mm:ss')]
      this.search()
    },
    exportExcel (data, index) {
      if (index === '1' && data.excelDownloadUrl) {
        this.downLoad(data.excelDownloadUrl) // 下载Excel
      } else if (index === '2' && data.imagesDownloadUrl) {
        this.downLoad(data.imagesDownloadUrl) // 下载图片
      }
    },
    output (row, index) {
      if (row.batchStatus === 2) {
        this.exportExcel(row, index)
      } else if (row.batchStatus === 3) {
        this.$Message.error('二维码生成失败')
      } else {
        getQRcodeInfo({
          merchantId: this.merchantId,
          activityBatchId: row.activityBatchId
        }).then(res => {
          const result = res.data || {}
          if (result.status === 200) {
            if (result.data.batchStatus === 2) {
              this.exportExcel(result.data, index)
            } else if (result.data.batchStatus === 3) {
              this.$Message.error('二维码生成失败')
            } else {
              this.$Message.error('二维码生成中，请稍后再试')
            }
          } else {
            this.$Message.error(`${result.error}`)
          }
        }).catch(err => {
          this.$Message.error(`${err}`)
        })
      }
    },
    downLoad (url) {
      const downloadElement = document.createElement('a')
      downloadElement.href = url
      downloadElement.download = url
      document.body.appendChild(downloadElement)
      downloadElement.click()
      document.body.removeChild(downloadElement)
    },
    skipAdd () {
      this.$router.push({ name: 'market_cardactivity_qrcode_create' })
    },
    changePageIndex (page) {
      this.pageIndex = page
      this.getData()
    },
    changePageSize (size) {
      this.pageSize = size
      this.search()
    },
    daterangeChange (daterange) {
      this.dateVal = daterange
    }
  }
}
</script>

<style lang='less'>
  .market_cardactivity_qrcode {
    .data-time-style {
      .ivu-input-wrapper {
        width: 280px;
      }
    }
  }
</style>
